package redis.client.nedis;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Getter;
import redis.client.nedis.reply.IReply;
import redis.client.nedis.request.RedisRequest;
import redis.client.nedis.request.RedisRequestQueue;

/**
 * Netty客户端消息处理
 *
 * @author gaodong
 */
@Getter
@ChannelHandler.Sharable
public class ReceiveClientHandler extends SimpleChannelInboundHandler<IReply<?>> {

    /**
     * 服务器地址
     */
    private HostAndPort hostAndPort;

    private RedisResultDeserializer redisResultDeserializer;

    public ReceiveClientHandler(HostAndPort hp) {
        this.hostAndPort = hp;
        redisResultDeserializer = new RedisResultDeserializer(hp);
        redisResultDeserializer.start();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, IReply<?> reply) {
        long s = System.nanoTime();
        RedisRequest rq = RedisRequestQueue.getInstance().pop(hostAndPort);
        rq.setReply(reply);
        rq.getCallback().accept(rq);
        //rq.releaseMutex();
        long e = System.nanoTime();
        //System.out.println("read=" + (e - s) / 1e6 + "ms");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) {
        cause.printStackTrace();
        channelHandlerContext.close();
    }
}
